/**
 * 网络请求工具类
 */
import config from '@/config';

// 存储会话信息
let sessionId = '';
let cookies = [];

// 创建请求对象
const request = (options) => {
  return new Promise((resolve, reject) => {
    // 构建请求参数
    const requestOptions = {
      url: options.url,
      method: options.method || 'GET',
      data: options.data || {},
      timeout: options.timeout || config.timeout || 15000,
      header: {
        'content-type': options.contentType || 'application/json',
        ...options.header
      },
      success: (res) => {
        console.log(`[请求成功] ${options.url}`, res);
        
        // 保存cookies
        if (res.cookies && res.cookies.length > 0) {
          cookies = res.cookies;
          console.log('保存cookies:', cookies);
          
          // 提取sessionId
          const sessionCookie = cookies.find(cookie => cookie.includes('SHIRO_SESSION_ID='));
          if (sessionCookie) {
            sessionId = sessionCookie.split('=')[1].split(';')[0];
            console.log('保存sessionId:', sessionId);
          }
        }
        
        // 检查响应内容类型
        const contentType = res.header && res.header['content-type'];
        
        // 如果返回的是HTML内容，可能是重定向到登录页或错误页
        if (contentType && contentType.includes('text/html')) {
          console.error('服务器返回了HTML内容，可能需要登录或会话已过期');
          reject({
            code: -2,
            message: '服务器返回了HTML内容，可能需要登录或会话已过期',
            error: res
          });
          return;
        }
        
        if (res.statusCode === 200) {
          // 处理返回的数据
          if (typeof res.data === 'string') {
            try {
              res.data = JSON.parse(res.data);
            } catch (e) {
              console.error('响应数据不是有效的JSON格式:', e);
              reject({
                code: -3,
                message: '服务器响应格式错误',
                error: e
              });
              return;
            }
          }
          
          resolve(res.data);
        } else {
          // 处理HTTP错误
          reject({
            code: res.statusCode,
            message: '服务器响应错误',
            error: res
          });
        }
      },
      fail: (err) => {
        console.error(`[请求失败] ${options.url}`, err);
        
        reject({
          code: -1,
          message: '网络错误，请稍后重试',
          error: err
        });
      },
      complete: () => {
        // 请求完成
      }
    };
    
    // 添加会话cookie
    if (cookies.length > 0) {
      requestOptions.header = requestOptions.header || {};
      requestOptions.header.Cookie = cookies.join('; ');
    }
    
    // 处理GET请求参数
    if ((options.method === 'GET' || !options.method) && options.data) {
      // 直接将参数附加到URL上，不使用URL对象（可能在某些环境下有兼容性问题）
      let queryParams = [];
      
      Object.keys(options.data).forEach(key => {
        if (options.data[key] !== undefined && options.data[key] !== null) {
          queryParams.push(`${encodeURIComponent(key)}=${encodeURIComponent(options.data[key])}`);
        }
      });
      
      // 添加参数到URL
      if (queryParams.length > 0) {
        const separator = requestOptions.url.includes('?') ? '&' : '?';
        requestOptions.url = `${requestOptions.url}${separator}${queryParams.join('&')}`;
      }
      
      // GET请求不需要在body中发送数据
      delete requestOptions.data;
    }
    
    // 请求前打印完整请求信息
    console.log('==== 发送请求 ====');
    console.log('请求URL:', requestOptions.url);
    console.log('请求方法:', requestOptions.method);
    console.log('请求头:', JSON.stringify(requestOptions.header));
    if (requestOptions.data) {
      console.log('请求数据:', JSON.stringify(requestOptions.data));
    }
    console.log('================');
    
    // 发送请求
    uni.request(requestOptions);
  });
};

// 设置会话ID和Cookie
export const setSession = (sessionData) => {
  if (sessionData.cookies) {
    cookies = sessionData.cookies;
    console.log('手动设置cookies:', cookies);
  }
  
  if (sessionData.sessionId) {
    sessionId = sessionData.sessionId;
    console.log('手动设置sessionId:', sessionId);
  }
};

// 清除会话信息
export const clearSession = () => {
  sessionId = '';
  cookies = [];
  console.log('清除会话信息');
};

// 创建请求实例
class Request {
  constructor(options = {}) {
    this.baseURL = options.baseURL || '';
    this.timeout = options.timeout || 6000;
  }

  request(options = {}) {
    options.url = this.baseURL + options.url;
    options.timeout = options.timeout || this.timeout;
    options.method = options.method || 'GET';
    
    // 添加会话cookie
    if (cookies.length > 0) {
      options.header = options.header || {};
      options.header.Cookie = cookies.join('; ');
    }
    
    return new Promise((resolve, reject) => {
      options.success = (response) => {
        // 保存cookies
        if (response.cookies && response.cookies.length > 0) {
          cookies = response.cookies;
          console.log('保存cookies:', cookies);
          
          // 提取sessionId
          const sessionCookie = cookies.find(cookie => cookie.includes('SHIRO_SESSION_ID='));
          if (sessionCookie) {
            sessionId = sessionCookie.split('=')[1].split(';')[0];
            console.log('保存sessionId:', sessionId);
          }
        }
        
        // 响应拦截
        resolve(response.data);
      };
      
      options.fail = (error) => {
        console.error(`[Error] ${options.method} ${options.url}`, error);
        reject(error);
      };
      
      // 请求前打印完整请求信息
      console.log('==== 发送请求 ====');
      console.log('请求URL:', options.url);
      console.log('请求方法:', options.method);
      console.log('请求头:', JSON.stringify(options.header));
      if (options.data) {
        console.log('请求数据:', JSON.stringify(options.data));
      }
      console.log('================');
      
      uni.request(options);
    });
  }

  get(url, params = {}) {
    return this.request({
      url,
      method: 'GET',
      data: params
    });
  }

  post(url, data = {}) {
    return this.request({
      url,
      method: 'POST',
      data
    });
  }
  
  put(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'PUT',
      data,
      ...options
    });
  }

  delete(url, data = {}, options = {}) {
    return this.request({
      url,
      method: 'DELETE',
      data,
      ...options
    });
  }
}

// 兼容ms.http格式的API
const ms = {
  base: config.baseUrl,
  manager: config.baseUrl + '/ms',
  http: {
    get: (url, params) => {
      return request({
        url,
        method: 'GET',
        data: params
      });
    },
    post: (url, data) => {
      return request({
        url,
        method: 'POST',
        data,
        contentType: 'application/x-www-form-urlencoded'
      });
    }
  },
  util: {
    openSystemUrl: (url) => {
      // 处理系统URL跳转
      if (url.startsWith('/index.do')) {
        uni.switchTab({ 
          url: '/pages/index/index',
          fail: (err) => {
            console.error('跳转失败:', err);
            uni.redirectTo({ url: '/pages/index/index' });
          }
        });
      } else {
        uni.navigateTo({
          url
        });
      }
    }
  }
};

// 全局挂载ms对象
if (typeof window !== 'undefined') {
  window.ms = ms;
} else if (typeof global !== 'undefined') {
  global.ms = ms;
}

export default Request;
export { ms, request }; 